﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;

public partial class Order_DistributeSettlementAmount : System.Web.UI.Page
{
    private string ReturnCode
    {
        get
        {
            return Request.QueryString["ReturnCode"] != null ? Request.QueryString["ReturnCode"].ToString() : "";
        }
    }

    private string OrderCode
    {
        get
        {
            return Request.QueryString["OrderCode"] != null ? Request.QueryString["OrderCode"].ToString() : "";
        }
    }

    private bool IsSecDeal
    {
        get
        {
            bool isSecDeal = false;
            if (ViewState["IsSecDeal"] != null)
            {
                isSecDeal = Convert.ToBoolean(ViewState["IsSecDeal"]);
            }
            return isSecDeal;
        }
        set
        {
            ViewState["IsSecDeal"] = value;
        }
    }
    
    private bool OrderIsClear
    {
        get
        {
            bool isClear = false;
            if (ViewState["OrderIsClear"] != null)
            {
                isClear = Convert.ToBoolean(ViewState["OrderIsClear"]);
            }
            return isClear;
        }
        set
        {
            ViewState["OrderIsClear"] = value;
        }
    }

    private Model.RETURNDOC ReturnDoc
    {
        get
        {
            Model.RETURNDOC returnDoc = null;
            if(ViewState["ReturnDoc"]!=null)
            {
                returnDoc = (Model.RETURNDOC)ViewState["ReturnDoc"];
            }
            return returnDoc;
        }
        set
        {
            ViewState["ReturnDoc"] = value;
        }
    }

    private Model.ORDERDOC OrderDoc
    {
        get
        {
            Model.ORDERDOC orderDoc = null;
            if (ViewState["OrderDoc"] != null)
            {
                orderDoc = (Model.ORDERDOC)ViewState["OrderDoc"];
            }
            return orderDoc;
        }
        set
        {
            ViewState["OrderDoc"] = value;
        }
    }

    private DataSet PayDetails
    {
        get
        {
            DataSet dst = null;
            if (ViewState["PayDetails"] != null)
            {
                dst = (DataSet)ViewState["PayDetails"];
            }
            return dst;
        }
        set
        {
            ViewState["PayDetails"] = value;
        }
    }

    private DataSet TempOrderPayDetails
    {
        get
        {
            DataSet dst = null;
            if (ViewState["TempOrderPayDetails"] != null)
            {
                dst = (DataSet)ViewState["TempOrderPayDetails"];
            }
            return dst;
        }
        set
        {
            ViewState["TempOrderPayDetails"] = value;
        }
    }

    private DataTable TempDataTable
    {
        get
        {
            DataTable tempTable = new BLL.RETURNDOCPAYDETAIL().CreateTempDataTable();
            //DataTable tempTable = null;
            if (ViewState["TempDataTable"] != null)
            {
                tempTable = (DataTable)ViewState["TempDataTable"];
            }
            return tempTable;
        }
        set
        {
            ViewState["TempDataTable"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Check.CheckPermission("400102");
        if (!IsPostBack)
        {
            GetDefaultData();
            BindReturnDocMain();
            if (this.IsSecDeal)
            {
                BindPayDetail();
            }
            else
            {
                pnlSecDeal.Visible = false;
            }
            this.TempDataTable = (new BLL.RETURNDOCPAYDETAIL().GetNotSECDealPayDetailById(this.ReturnCode)).Tables[0];
            BindDataListPayDocPayDetail(this.TempDataTable);

            btnCancel.Attributes.Add("onclick", "if(!confirm('要取消并返回上一页吗?'))return false;");
        }
        
    }

    private void GetDefaultData()
    {
        List<Model.RETURNTYPE> rtList = new BLL.RETURNTYPE().GetAllList();
        DropDownList2.DataSource = rtList;
        DropDownList2.DataTextField = "RT_NAME";
        DropDownList2.DataValueField = "RT_CODE";
        DropDownList2.DataBind();

        List<Model.USERS> uList = new BLL.USERS().GetList(String.Empty, " users_stop=0 ", " users_default desc ");
        DropDownList3.DataSource = uList;
        DropDownList3.DataTextField = "users_name";
        DropDownList3.DataValueField = "users_code";
        DropDownList3.DataBind();
    }

    private void BindReturnDocMain()
    {
        Model.RETURNDOC returnDoc = new BLL.RETURNDOC().GetModel(this.ReturnCode);
        if (returnDoc == null)
        {
            Response.Write("<script>alert('系统无法查询到该退货单信息！');location.href='../order/returndoc.aspx'</script>");
        }
        Model.ORDERDOC order = new BLL.ORDERDOC().GetModel(returnDoc.RD_DOCID);
        if (order == null)
        {
            Response.Write("<script>alert('系统无法查询到该退货单关联的订单信息！');location.href='../order/returndoc.aspx'</script>");
        }
        this.OrderIsClear = order.ORDER_CLEAR == 1 ? true : false;
        this.IsSecDeal = order.ORDER_SECDEAL == 1 ? true : false;
        this.ReturnDoc = returnDoc;
        this.OrderDoc = order;
        /////////////////////////

        DataSet ds = new BLL.RETURNDOC().GetModelDataSet(this.ReturnCode);
        DataTable dt = ds.Tables[0];
        lbldm.Text = dt.Rows[0]["RD_ID"].ToString();
        lblorder.Text = dt.Rows[0]["RD_DOCID"].ToString();
        lblorder.NavigateUrl = "~/Order/OrderDetail.aspx?code=" + dt.Rows[0]["RD_DOCID"].ToString().Trim();
        lblgmr.Text = dt.Rows[0]["gkmc"].ToString();
        //绑定物流公司
        List<Model.TRANER> traner = new BLL.TRANER().GetAllList();
        ddlwlgs.DataSource = traner;
        ddlwlgs.DataTextField = "TRANER_NAME";
        ddlwlgs.DataValueField = "TRANER_CODE";
        ddlwlgs.DataBind();
        txtwlfy.Text = Decimal.Round((Decimal)dt.Rows[0]["RD_TRANCOST"], 2).ToString();
        txtthr.Text = dt.Rows[0]["RD_RETURNER"].ToString();
        Label14.Text = Decimal.Round((Decimal)dt.Rows[0]["RD_TRANCOST"], 2).ToString();
        txtthrdh.Text = dt.Rows[0]["RD_RETURNPHONE1"].ToString();
        txtthrsj.Text = dt.Rows[0]["RD_RETURNERPHONE2"].ToString();
        Label7.Text = dt.Rows[0]["RD_TRANID"].ToString();
        txtthryb.Text = dt.Rows[0]["RD_RETURNPOSTCODE"].ToString();
        Label9.Text = dt.Rows[0]["RD_NOTE"].ToString();
        txtthrdz.Text = dt.Rows[0]["RD_RETURNADDRESS"].ToString();

        //ddlfyxz.SelectedValue = dt.Rows[0]["RD_COSTTYPE"].ToString().Trim();
        //Label12.Text = dt.Rows[0]["RD_RETURNTYPE"].ToString().Trim() == "000" ? "结余款" : "其  他";
        Label13.Text = dt.Rows[0]["RD_AAMT"].ToString();
        Label14.Text = dt.Rows[0]["RD_SUBITG"].ToString();
        CheckBox1.Checked = dt.Rows[0]["RD_CHECK"].ToString() == "1" ? true : false;
        CheckBox2.Checked = dt.Rows[0]["RD_CLEAR"].ToString() == "1" ? true : false;
        CheckBox3.Checked = dt.Rows[0]["RD_DELETE"].ToString() == "1" ? true : false;
        Label15.Text = Decimal.Round((Decimal)dt.Rows[0]["RD_CLEAREDAMT"], 2).ToString();
        //if (CheckBox1.Checked || CheckBox3.Checked)
        //{
        //    ((Button)BUTTONDJ1.Controls[14]).Enabled = false;
        //    ((Button)BUTTONDJ1.Controls[6]).Enabled = false;
        //    ((Button)BUTTONDJ1.Controls[4]).Visible = false;
        //}
        //btnClear.Visible = dt.Rows[0]["RD_SECDEAL"].ToString() == "1" ? true : false;
        //btnClear.Enabled = dt.Rows[0]["RD_CHECK"].ToString() == "1" ? true : false;
        //if (dt.Rows[0]["RD_CHECK"].ToString() == "1")
        //{
        //    btnClear.Enabled = dt.Rows[0]["RD_CLEAR"].ToString() == "1" ? false : true;
        //}
        DropDownList2.SelectedValue = dt.Rows[0]["RD_REASON"].ToString();
        DropDownList3.SelectedValue = dt.Rows[0]["RD_DUTY"].ToString();
    }

    private void BindPayDetail()
    {
        DataSet dst = new BLL.PAYDETAIL().GetPayDetailByDetailIdAndDtType(this.OrderCode, "002");
        this.TempOrderPayDetails = new BLL.RETURNDOCPAYDETAIL().GetSECDealPayDetailById(this.ReturnCode);
        if (dst.Tables[0].Rows.Count == 0)
        {
            Response.Write("<script>alert('系统无法查询到该退货单关联的订单的担保交易支付明细！');location.href='../order/returndoc.aspx'</script>"); 
        }
        this.PayDetails = dst;
        dlistPayDetail.DataSource = dst;
        dlistPayDetail.DataBind();
        hidOrderPayDetailCount.Value = dst.Tables[0].Rows.Count.ToString();

        decimal amount = 0.00M;
        for (int i = 0; i < this.TempOrderPayDetails.Tables[0].Rows.Count; i++)
        {
            amount += Convert.ToDecimal(this.TempOrderPayDetails.Tables[0].Rows[i]["RDPD_PAYAMT"]);
        }
         txtReverseAmount.Text = string.Format("{0:0.00}", amount);
         txtReturnTotal.Text = string.Format("{0:0.00}", amount + Convert.ToDecimal(txtReturnAmount.Text.Trim()));
    
        
    }

    private void BindDropPayType(string dealType, DropDownList drop)
    {
        DataSet dst = new BLL.PAYTYPE_DEALTYPE().P_DealType_GetPayTypeByCode(dealType);
        ListItem tempItem;
        drop.Items.Clear();
        for (int i = 0; i < dst.Tables[0].Rows.Count; i++)
        {
            tempItem = new ListItem();
            tempItem.Text = dst.Tables[0].Rows[i]["PT_NAME"].ToString();
            tempItem.Value = dst.Tables[0].Rows[i]["PT_CODE"].ToString() + "|" + dst.Tables[0].Rows[i]["PT_HAVEDEAL"].ToString();
            drop.Items.Add(tempItem);
        }

    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (!Check.CheckPermission("400102", "00002"))
        {
            Share.Alert(this.Page, "无权操作"); return;
        }
        try
        {
            FillValueIntoDataTable(this.TempDataTable);
            if (Convert.ToDecimal(hidReturnTotal.Value) > Convert.ToDecimal(Label13.Text))
            {
                Share.Alert(this.Page, "填写的退款总额不能大于退款单退款总额！"); return;
            }

            DataSet dstPayDetailRecordCount = new BLL.PAYDETAIL().GetRecordCount(this.OrderCode);
            DataSet dstPayDetailMaxDetailId = new BLL.PAYDETAIL().GetMaxDetailId(this.OrderCode);
            DataSet dstMaxDetailId = new BLL.RETURNDOCPAYDETAIL().GetMaxDetailId(this.ReturnCode);

            int payDetailMaxDetailId = 0;
            int maxDetailId = 0;//strMaxDetailId
            if (dstMaxDetailId.Tables[0].Rows.Count > 0)
            {
                maxDetailId = Convert.ToInt32(dstMaxDetailId.Tables[0].Rows[0]["MaxDetailId"]);
            }
            if (dstPayDetailMaxDetailId.Tables[0].Rows.Count > 0)
            {
                payDetailMaxDetailId = Convert.ToInt32(dstPayDetailMaxDetailId.Tables[0].Rows[0]["MaxDetailId"]);
            }



            #region 订单已结算
            if (this.OrderIsClear)
            {
                if (this.TempDataTable != null)
                {
                    decimal payAmount = 0;
                    for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                    {
                        if (Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]) < 0)
                        {
                            throw new Exception("请填写数值为正数的退款金额！");
                        }
                        payAmount += Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]);
                    }
                    if (payAmount > Convert.ToDecimal(Label13.Text))
                    {
                        throw new Exception("您填写的退款总额大于退货单退款总额，请核对！");
                    }

                    StringBuilder strSql = new StringBuilder();
                    strSql.Append("DELETE FROM RETURNDOCPAYDETAIL WHERE RDPD_ID='");
                    strSql.Append(this.ReturnCode);
                    strSql.Append("'|");

                    if (maxDetailId == 0)
                    {
                        for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                        {
                            strSql.Append("INSERT INTO [RETURNDOCPAYDETAIL]([RDPD_ID],[RDPD_DETAILID],[RDPD_PAYTYPE],[RDPD_PAYAMT],");
                            strSql.Append("[RDPD_PAYDATE],[RDPD_DEALID],[RDPD_DEALDATE],[RDPD_ACCOUNT],[RDPD_NOTE],[RDPD_DTCODE]) VALUES('");
                            strSql.Append(this.ReturnCode);
                            strSql.Append("','");
                            strSql.Append(i + 1);
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYTYPE"].ToString());
                            strSql.Append("',");
                            strSql.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                            strSql.Append(",'");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYDATE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALID"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALDATE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_ACCOUNT"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_NOTE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString());
                            strSql.Append("')|");
                        }
                    }
                    else
                    {
                        for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                        {
                            strSql.Append("INSERT INTO [RETURNDOCPAYDETAIL]([RDPD_ID],[RDPD_DETAILID],[RDPD_PAYTYPE],[RDPD_PAYAMT],");
                            strSql.Append("[RDPD_PAYDATE],[RDPD_DEALID],[RDPD_DEALDATE],[RDPD_ACCOUNT],[RDPD_NOTE],[RDPD_DTCODE]) VALUES('");
                            strSql.Append(this.ReturnCode);
                            strSql.Append("','");
                            strSql.Append(maxDetailId + i + 1);
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYTYPE"].ToString());
                            strSql.Append("',");
                            strSql.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                            strSql.Append(",'");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYDATE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALID"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALDATE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_ACCOUNT"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_NOTE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString());
                            strSql.Append("')|");
                        }
                    }

                    string stringSql = strSql.ToString();
                    if (stringSql == "")
                    {
                        Response.Redirect("~/order/returndocedit.aspx?code=" + this.ReturnCode);
                    }
                    char[] charToTrim = new char[] { '|' };
                    string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                    if (new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray))
                    {
                        //Response.Write("<script>alert('生成结算单成功！');window.close();</script>");
                        //Response.Write("<script>alert('生成结算单成功！');location.href='settlementdetails.aspx?code=" + newPayDocId + "'</script>");
                        Share.InsertLog("400102", "00002");
                        Response.Redirect("../order/returndocedit.aspx?code=" + this.ReturnCode);
                    }
                    else
                    {
                        Response.Write("<script>alert('生成结算单失败，请重新编辑！');</script>");
                    }
                }
            }
            #endregion
            #region 订单未计算
            else
            {
                StringBuilder strSql = new StringBuilder();
                strSql.Append("DELETE FROM RETURNDOCPAYDETAIL WHERE RDPD_ID='");
                strSql.Append(this.ReturnCode);
                strSql.Append("'|");

                Label lblDetailId;
                TextBox txtReturnAmount;
                bool isUseAllocation = true;
                decimal amount = 0;

                foreach (DataListItem temp in dlistPayDetail.Items)
                {
                    txtReturnAmount = (TextBox)temp.FindControl("txtReturnAmount");
                    if (Convert.ToDecimal(txtReturnAmount.Text.Trim()) < 0)
                    {
                        throw new Exception("请填写数值为正数的退款金额！");
                    }
                    amount += Convert.ToDecimal(txtReturnAmount.Text.Trim());
                }

                if (amount == 0)
                {
                    isUseAllocation = false;
                }

                for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                {
                    if (Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]) < 0)
                    {
                        throw new Exception("请填写数值为正数的退款金额！");
                    }
                    amount += Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]);
                }

                if (amount > Convert.ToDecimal(Label13.Text))
                {
                    throw new Exception("您填写的退款总额大于指定的退款总金额！");
                }

                if (this.OrderDoc.ORDER_SECDEAL == 1)
                {
                    if (isUseAllocation)
                    {
                        for (int i = 0; i < dlistPayDetail.Items.Count; i++)
                        {
                            txtReturnAmount = (TextBox)dlistPayDetail.Items[i].FindControl("txtReturnAmount");
                            lblDetailId = (Label)dlistPayDetail.Items[i].FindControl("lblDetailId");

                            if (Convert.ToDecimal(txtReturnAmount.Text.Trim()) > 0)
                            {
                                strSql.Append("INSERT INTO [RETURNDOCPAYDETAIL]([RDPD_ID],[RDPD_DETAILID],[RDPD_PAYTYPE],[RDPD_PAYAMT],");
                                strSql.Append("[RDPD_PAYDATE],[RDPD_DEALID],[RDPD_DEALDATE],[RDPD_ACCOUNT],[RDPD_NOTE],[RDPD_DTCODE]) VALUES('");
                                strSql.Append(this.ReturnCode);
                                strSql.Append("','");
                                strSql.Append(lblDetailId.Text);
                                strSql.Append("','");
                                strSql.Append(this.PayDetails.Tables[0].Rows[i]["PD_PAYTYPE"].ToString());
                                strSql.Append("',");
                                strSql.Append(Convert.ToDecimal(txtReturnAmount.Text.Trim()));
                                strSql.Append(",'");
                                strSql.Append(DateTime.Now);
                                strSql.Append("','");
                                strSql.Append(this.PayDetails.Tables[0].Rows[i]["PD_DEALID"].ToString());
                                strSql.Append("','");
                                strSql.Append(Convert.ToDateTime(this.PayDetails.Tables[0].Rows[i]["PD_DEALDATE"]));
                                strSql.Append("','");
                                strSql.Append(this.PayDetails.Tables[0].Rows[i]["PD_ACCOUNT"].ToString());
                                strSql.Append("','','002')|");
                            }


                        }
                        if (maxDetailId >= payDetailMaxDetailId)
                        {
                            for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                            {
                                strSql.Append("INSERT INTO [RETURNDOCPAYDETAIL]([RDPD_ID],[RDPD_DETAILID],[RDPD_PAYTYPE],[RDPD_PAYAMT],");
                                strSql.Append("[RDPD_PAYDATE],[RDPD_DEALID],[RDPD_DEALDATE],[RDPD_ACCOUNT],[RDPD_NOTE],[RDPD_DTCODE]) VALUES('");
                                strSql.Append(this.ReturnCode);
                                strSql.Append("','");
                                strSql.Append(maxDetailId + i + 1);
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYTYPE"].ToString());
                                strSql.Append("',");
                                strSql.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                                strSql.Append(",'");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYDATE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALID"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALDATE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_ACCOUNT"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_NOTE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString());
                                strSql.Append("')|");
                            }
                        }
                        else
                        {
                            for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                            {
                                strSql.Append("INSERT INTO [RETURNDOCPAYDETAIL]([RDPD_ID],[RDPD_DETAILID],[RDPD_PAYTYPE],[RDPD_PAYAMT],");
                                strSql.Append("[RDPD_PAYDATE],[RDPD_DEALID],[RDPD_DEALDATE],[RDPD_ACCOUNT],[RDPD_NOTE],[RDPD_DTCODE]) VALUES('");
                                strSql.Append(this.ReturnCode);
                                strSql.Append("','");
                                strSql.Append(payDetailMaxDetailId + i + 1);
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYTYPE"].ToString());
                                strSql.Append("',");
                                strSql.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                                strSql.Append(",'");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYDATE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALID"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALDATE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_ACCOUNT"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_NOTE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString());
                                strSql.Append("')|");
                            }
                        }

                    }
                    else
                    {
                        if (maxDetailId >= Convert.ToInt32(dstPayDetailRecordCount.Tables[0].Rows[0]["RecordCount"]))
                        {
                            for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                            {
                                strSql.Append("INSERT INTO [RETURNDOCPAYDETAIL]([RDPD_ID],[RDPD_DETAILID],[RDPD_PAYTYPE],[RDPD_PAYAMT],");
                                strSql.Append("[RDPD_PAYDATE],[RDPD_DEALID],[RDPD_DEALDATE],[RDPD_ACCOUNT],[RDPD_NOTE],[RDPD_DTCODE]) VALUES('");
                                strSql.Append(this.ReturnCode);
                                strSql.Append("','");
                                strSql.Append(maxDetailId + i + 1);
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYTYPE"].ToString());
                                strSql.Append("',");
                                strSql.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                                strSql.Append(",'");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYDATE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALID"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALDATE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_ACCOUNT"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_NOTE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString());
                                strSql.Append("')|");
                            }
                        }
                        else
                        {
                            for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                            {
                                strSql.Append("INSERT INTO [RETURNDOCPAYDETAIL]([RDPD_ID],[RDPD_DETAILID],[RDPD_PAYTYPE],[RDPD_PAYAMT],");
                                strSql.Append("[RDPD_PAYDATE],[RDPD_DEALID],[RDPD_DEALDATE],[RDPD_ACCOUNT],[RDPD_NOTE],[RDPD_DTCODE]) VALUES('");
                                strSql.Append(this.ReturnCode);
                                strSql.Append("','");
                                strSql.Append(Convert.ToInt32(dstPayDetailRecordCount.Tables[0].Rows[0]["RecordCount"]) + i + 1);
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYTYPE"].ToString());
                                strSql.Append("',");
                                strSql.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                                strSql.Append(",'");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYDATE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALID"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALDATE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_ACCOUNT"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_NOTE"].ToString());
                                strSql.Append("','");
                                strSql.Append(this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString());
                                strSql.Append("')|");
                            }
                        }
                    }
                }
                else
                {
                    if (maxDetailId == 0)
                    {
                        for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                        {
                            strSql.Append("INSERT INTO [RETURNDOCPAYDETAIL]([RDPD_ID],[RDPD_DETAILID],[RDPD_PAYTYPE],[RDPD_PAYAMT],");
                            strSql.Append("[RDPD_PAYDATE],[RDPD_DEALID],[RDPD_DEALDATE],[RDPD_ACCOUNT],[RDPD_NOTE],[RDPD_DTCODE]) VALUES('");
                            strSql.Append(this.ReturnCode);
                            strSql.Append("','");
                            strSql.Append(i + 1);
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYTYPE"].ToString());
                            strSql.Append("',");
                            strSql.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                            strSql.Append(",'");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYDATE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALID"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALDATE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_ACCOUNT"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_NOTE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString());
                            strSql.Append("')|");
                        }
                    }
                    else
                    {
                        for (int i = 0; i < this.TempDataTable.Rows.Count; i++)
                        {
                            strSql.Append("INSERT INTO [RETURNDOCPAYDETAIL]([RDPD_ID],[RDPD_DETAILID],[RDPD_PAYTYPE],[RDPD_PAYAMT],");
                            strSql.Append("[RDPD_PAYDATE],[RDPD_DEALID],[RDPD_DEALDATE],[RDPD_ACCOUNT],[RDPD_NOTE],[RDPD_DTCODE]) VALUES('");
                            strSql.Append(this.ReturnCode);
                            strSql.Append("','");
                            strSql.Append(maxDetailId + i + 1);
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYTYPE"].ToString());
                            strSql.Append("',");
                            strSql.Append(Convert.ToDecimal(this.TempDataTable.Rows[i]["RDPD_PAYAMT"]));
                            strSql.Append(",'");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_PAYDATE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALID"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DEALDATE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_ACCOUNT"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_NOTE"].ToString());
                            strSql.Append("','");
                            strSql.Append(this.TempDataTable.Rows[i]["RDPD_DTCODE"].ToString());
                            strSql.Append("')|");
                        }
                    }
                }                

                string stringSql = strSql.ToString();
                if (stringSql == "")
                {
                    Response.Redirect("~/order/returndocedit.aspx?code=" + this.ReturnCode);
                }
                char[] charToTrim = new char[] { '|' };
                string[] sqlCommandArray = stringSql.TrimEnd(charToTrim).Split(charToTrim);
                if (new SQLServerDAL.ORDERDOC().Deliver(sqlCommandArray))
                {
                    //Response.Write("<script>alert('退货金额修改成功！');location.href='settlementdetails.aspx?code=" + newPayDocId + "'</script>");
                    Share.InsertLog("400102", "00002");
                    Response.Redirect("~/order/returndocedit.aspx?code=" + this.ReturnCode);
                }
                else
                {
                    Response.Write("<script>alert('退货金额修改失败，请重新修改！');</script>");
                }
            }  
            #endregion
            
        }
        catch (FormatException ex)
        {
            Share.Alert(this.Page,"请填写正确的金额！");
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    
    }

    protected void dlistPayDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Label lblDetailId = (Label)e.Item.FindControl("lblDetailId");
            TextBox txtReturnAmount = (TextBox)e.Item.FindControl("txtReturnAmount");
            for(int i=0;i<this.TempOrderPayDetails.Tables[0].Rows.Count;i++)
            {
                if (lblDetailId.Text == this.TempOrderPayDetails.Tables[0].Rows[i]["RDPD_DETAILID"].ToString())
                {
                    txtReturnAmount.Text = String.Format("{0:0.00}", this.TempOrderPayDetails.Tables[0].Rows[i]["RDPD_payamt"]);
                    break;
                }
            }
            
            if (this.OrderIsClear)
            {
                txtReturnAmount.Enabled = false;
            }
        }
    }

    protected void btnAddPayDocPayDetail_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.TempDataTable == null)
            {
                this.TempDataTable = new BLL.PAYDOCPAYDETAIL().CreateTempDataTable();
            }
            else
            {
                FillValueIntoDataTable(this.TempDataTable);
            }
            this.TempDataTable = new BLL.RETURNDOCPAYDETAIL().AddDataRowToDataTable(this.TempDataTable);
            BindDataListPayDocPayDetail(this.TempDataTable);
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }
    }

    private void FillValueIntoDataTable(DataTable tbl)
    {
        DropDownList dropDealType;
        DropDownList dropPayType;
        TextBox txtPayAmount;
        TextBox txtPayDate;
        TextBox txtDealID;
        TextBox txtDealDate;
        TextBox txtAccount;
        TextBox txtNotes;

        for (int i = 0; i < dlistPayDocPayDetail.Items.Count; i++)
        {
            dropDealType = (DropDownList)dlistPayDocPayDetail.Items[i].FindControl("dropDealType");
            dropPayType = (DropDownList)dlistPayDocPayDetail.Items[i].FindControl("dropPayType");
            txtPayAmount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayAmount");
            txtPayDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtPayDate");
            txtDealID = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealID");
            txtDealDate = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtDealDate");
            txtAccount = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtAccount");
            txtNotes = (TextBox)dlistPayDocPayDetail.Items[i].FindControl("txtNotes");

            string[] selectValue = dropPayType.SelectedItem.Value.Split('|');
            if (selectValue[1] == "1" && txtDealID.Text.Trim() == "")
            {
                throw new Exception("您选择的支付方式必须输入交易号，请输入！");
            }

            tbl.Rows[i]["RDPD_DTCODE"] = dropDealType.SelectedValue;
            tbl.Rows[i]["RDPD_PAYTYPE"] = selectValue[0];
            tbl.Rows[i]["RDPD_PAYAMT"] = Convert.ToDecimal(txtPayAmount.Text.Trim());
            tbl.Rows[i]["RDPD_PAYDATE"] = Convert.ToDateTime(txtPayDate.Text.Trim());
            tbl.Rows[i]["RDPD_DEALID"] = txtDealID.Text.Trim();
            tbl.Rows[i]["RDPD_DEALDATE"] = Convert.ToDateTime(txtDealDate.Text.Trim());
            tbl.Rows[i]["RDPD_ACCOUNT"] = txtAccount.Text.Trim();
            tbl.Rows[i]["RDPD_NOTE"] = txtNotes.Text.Trim();
        }

    }

    protected void dlistPayDocPayDetail_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DropDownList dropDealType = (DropDownList)e.Item.FindControl("dropDealType");
            for (int i = 0; i < dropDealType.Items.Count; i++)
            {
                if (dropDealType.Items[i].Value == this.TempDataTable.Rows[e.Item.ItemIndex]["RDPD_DTCODE"].ToString())
                {
                    dropDealType.SelectedIndex = i;
                    break;
                }
            }

            DropDownList dropPayType = (DropDownList)e.Item.FindControl("dropPayType");

            if (dropPayType != null)
            {
                if (this.TempDataTable.Rows[e.Item.ItemIndex]["RDPD_DTCODE"].ToString() != "")
                {
                    BindDropPayType(this.TempDataTable.Rows[e.Item.ItemIndex]["RDPD_DTCODE"].ToString(), dropPayType);
                    for (int i = 0; i < dropPayType.Items.Count; i++)
                    {
                        if (dropPayType.Items[i].Value.Contains(this.TempDataTable.Rows[e.Item.ItemIndex]["RDPD_PAYTYPE"].ToString() + "|"))
                        {
                            dropPayType.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else
                {
                    BindDropPayType(dropDealType.Items[0].Value, dropPayType);
                }


            }
        }
    }

    protected void dlistPayDocPayDetail_ItemCommand(object source, DataListCommandEventArgs e)
    {
        try
        {
            if (e.CommandName.ToLower() == "del")
            {
                FillValueIntoDataTable(this.TempDataTable);

                BindDataListPayDocPayDetail(new BLL.PAYDOCPAYDETAIL().SubDataRowFromDataTable(this.TempDataTable, e.Item.ItemIndex));

                
            }
        }
        catch (Exception ex)
        {
            Share.Alert(this.Page, ex.Message);
        }

    }

    private void BindDataListPayDocPayDetail(DataTable tbl)
    {
        dlistPayDocPayDetail.DataSource = tbl;
        dlistPayDocPayDetail.DataBind();
        hidReturnDocPayDetailCount.Value = tbl.Rows.Count.ToString();
        decimal amount = 0.00M;
        for (int i = 0; i < tbl.Rows.Count; i++)
        {
            amount += Convert.ToDecimal(tbl.Rows[i]["RDPD_PAYAMT"]);
        }
        txtReturnAmount.Text = string.Format("{0:0.00}", amount);
        txtReturnTotal.Text = string.Format("{0:0.00}", amount + Convert.ToDecimal(txtReverseAmount.Text.Trim()));
    }

    protected void DataList2_DDLCHANGE_Click(object sender, EventArgs e)
    {
        DropDownList dropDealType = (DropDownList)sender;
        DropDownList dropPayType = (DropDownList)dropDealType.Parent.FindControl("dropPayType");
        BindDropPayType(dropDealType.SelectedValue, dropPayType);
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("~/order/ReturnDocEdit.aspx?code=" + this.ReturnCode);
    }
}
